﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Declaratie.Models;
using System.Data.Entity;
using Declaratie.Models.Mapping;

namespace Declaratie.Controllers
{
    public class ProjectContext : DbContext
    {
        public DbSet<Project> Projects { get; set; }
        public DbSet<ConsortiumPartner> ConsortiumPartners { get; set; }

        protected override void OnModelCreating(DbModelBuilder mb)
        {
            mb.Entity<Project>()
                .HasMany(p => p.Activiteiten)
                .WithOptional();

            mb.Entity<Project>()
                .HasMany(p => p.ConsortiumPartners)
                .WithRequired();

            mb.Entity<ConsortiumPartner>()
                .HasMany(c => c.Medewerkers)
                .WithRequired();

            mb.Entity<Medewerker>()
                .HasMany(m => m.Activiteiten)
                .WithOptional();
        }
    }

    public class ProjectRepository
    {
        public Project GetProjectById(int projectId)
        {
            return GetAllProjects().FirstOrDefault(x => x.ProjectId == projectId);
        }

        public Project AddProject(Project project){
            Project p = new Project();
            using (var db = new ProjectContext())
            {
                p = db.Projects.Add(project);
                db.SaveChanges();
            }
            return p;
        }

        public List<Project> GetAllProjects()
        {
            using (var db = new ProjectContext())
            {
                return db.Projects
                    .Include(x => x.ConsortiumPartners.Select(y=>y.Medewerkers.Select(z=>z.Activiteiten)))
                    .Include(x => x.Activiteiten)
                    .ToList();
            }
        }

        public void DeleteProject(int projectId)
        {
            using (var db = new ProjectContext())
            {
                db.Projects.Remove(GetProjectById(projectId));
            }
        }
    }


}